package 力扣链表;

public class Leedcode21合并两个有序链表 {
    //方法1
    public ListNode mergeTwoLists1(ListNode list1, ListNode list2) {
        //虚拟头节点
        ListNode head = new ListNode();
        ListNode cur = head;
        while (list1 != null && list2 != null){
            if (list1.val <= list2.val){
                cur.next = list1;
                cur = list1;
                list1 = list1.next;
            }else {
                cur.next = list2;
                cur = list2;
                list2 = list2.next;
            }
        }
        if (list1 == null){
            cur.next = list2;
        }
        if (list2 == null){
            cur.next = list1;
        }
        return head.next;
    }
    //方法2：递归
    /**
     * 传入两个链表list1和list2就能拼接成一个有序的单链表，返回头节点
     * @param list1
     * @param list2
     * @return
     */
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        //递归结束条件
        if (list1 == null){
            return list2;
        }
        if (list2 == null){
            return list1;
        }
        if (list1.val <= list2.val){
            list1.next = mergeTwoLists(list1.next,list2);
            return list1;
        }else {
            list2.next = mergeTwoLists(list1,list2.next);
            return list2;
        }
    }
}
